#!/usr/bin/env python

# http://www.linuxjournal.com/article/6586?page=0,2

import sys
import gobject

try:
    import pygtk
    pygtk.require('2.0')
except:
    pass

try:
    import gtk
    import gtk.glade
except:
    print "You need to install pyGTK or GTKv2 ",
    print "or set your PYTHONPATH correctly."
    print "try: export PYTHONPATH=",
    print "/usr/local/lib/python2.2/site-packages/"
    sys.exit(1)

def insert_row(model, parent, firstcolumn, secondcolumn):
    myiter = model.insert_after(parent, None)
    model.set_value(myiter, 0, firstcolumn)
    model.set_value(myiter, 1, secondcolumn)
    return myiter

class appgui:
    def __init__(self):
        gladefile = 'glade-demo.glade'
        windowname = 'window1'
        self.glade = gtk.glade.XML(gladefile, windowname)

        self.logwindowview = self.glade.get_widget('textview1')
        self.logwindow = gtk.TextBuffer(None)
        self.logwindowview.set_buffer(self.logwindow)

        self.treeview = self.glade.get_widget('treeview1')
        self.treemodel = gtk.TreeStore(gobject.TYPE_STRING, gobject.TYPE_STRING)
        self.treeview.set_model(self.treemodel)

        self.treeview.set_headers_visible(True)
        
        renderer = gtk.CellRendererText()
        column = gtk.TreeViewColumn('Name', renderer, text=0)
        column.set_resizable(True)
        self.treeview.append_column(column)

        renderer = gtk.CellRendererText()
        column = gtk.TreeViewColumn('Description', renderer, text=1)
        column.set_resizable(True)
        self.treeview.append_column(column)

        model = self.treemodel
        insert_row(model, None, 'Helium', 'Control Current Helium')
        syscallIter = insert_row(model, None, 'Syscall Redir', 'Control Current Syscall Redir')
        insert_row(model, syscallIter, 'Syscall-shell', 'Pop-up a syscall-shell')
        
        self.treeview.show()

        #very important for you to be able to close2exit the window
        self.glade.get_widget('window1').connect('destroy', (gtk.main_quit))

        self.glade.signal_autoconnect(self)

        return

    def on_window1_delete(self, widget, ev, data=None):
        print "window1_delete"
        return False

    def on_button1_clicked(self, widget):
        host = self.glade.get_widget('entry1').get_text()
        port = int(self.glade.get_widget('spinbutton1').get_value())
        if host == '':
            return

        import urllib
        page = urllib.urlopen('http://' + host + ':' + str(port) + '/')
        data = page.read()

        u = data.decode('utf-8', 'ignore')
        self.logwindow.insert_at_cursor(u, len(u))


if __name__ == '__main__':
    app = appgui()
    gtk.main()

